package com.munhrasoft.dinamica.converters;

import java.util.logging.Logger;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.munhrasoft.dinamica.business.entities.GroupEntity;
import com.munhrasoft.dinamica.business.logic.UserEJB;

@FacesConverter(value = "groupEntityConverter")
public class GroupEntityConverter implements Converter {

    private UserEJB       userEJB;

    private static Logger logger = Logger.getLogger(GroupEntityConverter.class.getName());

    public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {

        logger.info("getAsObject Validation Result " + arg0.isValidationFailed());

        try {
            userEJB = (UserEJB) new InitialContext().lookup("java:global/dinamica-control/UserEJB");
        } catch (NamingException e) {
            // TODO Incluir aqui uma mensagem comum pois algo fatal aconteceu
            e.printStackTrace();
        }

        if (arg2 == null) {
            logger.info("Group Converter arg2 null ");
            return null;
        } else {
            logger.info("Group Converter arg2 not null returning query " + userEJB.findGroupByName(arg2).get(0));
            return userEJB.findGroupByName(arg2).get(0);
        }
    }

    public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
        logger.info(" getAsString Validation Result " + arg0.isValidationFailed());
        if (arg2 == null) {
            return null;
        } else {
            return ((GroupEntity) arg2).getItsName();
        }
    }
}
